package com.learnyou.server.xingzuo.biz.common.impl;

import cn.hutool.core.util.RandomUtil;
import org.springframework.stereotype.Service;
import com.learnyou.server.xingzuo.biz.common.SmsSendBiz;
import com.learnyou.server.xingzuo.biz.helper.SmsHelper;
import com.learnyou.server.xingzuo.common.config.SmsConfig;
import com.learnyou.server.xingzuo.common.constants.RedisConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author heweifeng
 * @Description:
 * @date 2022/12/3 15:39
 */
@Slf4j
@AllArgsConstructor
@Service
public class SmsSendBizImpl implements SmsSendBiz {

    private final SmsConfig smsConfig;
    private final RedisTemplate<String, String> redisTemplate;

    @Override
    public Boolean sendVerifyCode(String phone) {

        String verifyCode = RandomUtil.randomNumbers(6);
        log.info("本次验证码->"+verifyCode);
        redisTemplate.opsForValue().set(RedisConstants.REGISTER_VERIFY_CODE_PREFIX+phone, verifyCode, smsConfig.getVerifyExpire(), TimeUnit.MINUTES);
        return SmsHelper.sendSms(smsConfig, phone, smsConfig.getVerifyCodeTemplate(), new String[]{verifyCode, smsConfig.getVerifyExpire().toString()});

    }

    @Override
    public Boolean checkVerifyCode(String phone, String code) {

        String myCode = redisTemplate.opsForValue().get(RedisConstants.REGISTER_VERIFY_CODE_PREFIX + phone);
        if (Objects.equals(code, myCode)){
            redisTemplate.opsForValue().getAndDelete(RedisConstants.REGISTER_VERIFY_CODE_PREFIX + phone);
            return true;
        }else {
            return false;
        }
    }
}
